<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"> </el-alert>
      <el-row class="row">
        <el-col>
          <span>
            选择商品分类：
            <el-cascader v-model="cateCascaderId" :options="catelist" :props="cascaderProps" expandTrigger:='hover' @change="handleChange"></el-cascader>
          </span>
        </el-col>
      </el-row>
        <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="动态属性" name="many">
        <el-button type="primary" size="mini" :disabled="isDisable" @click="addDialogVisible=true">添加参数</el-button>
         <el-table :data="manyactiveName" style="width: 100%" border stripe>
       <el-table-column type="expand">
        <template slot-scope="scope">
              <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleRemoveTag(i,scope.row)">{{item}}</el-tag>
<el-input class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
        </template>
       </el-table-column>
      <el-table-column label="#" type="index">  </el-table-column>
      <el-table-column
        prop="attr_name"
        label="分类名称">
      </el-table-column>
      <el-table-column
        label="操作">
      <template slot-scope="scope">
           <el-button type="primary" icon="el-icon-edit" size="mini" @click="showDialog(scope.row.attr_id)">操作</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParamsData(scope.row.attr_id)">删除</el-button>
      </template>
      </el-table-column>
    </el-table>
    </el-tab-pane>
    <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" size="mini" :disabled="isDisable" @click="addDialogVisible=true">添加属性</el-button>
        <el-table :data="onlyactiveName" style="width: 100%" border stripe>
       <el-table-column type="expand">
           <template slot-scope="scope">
              <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleRemoveTag(i,scope.row)">{{item}}</el-tag>
<el-input class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
        </template>
       </el-table-column>
      <el-table-column label="#" type="index">  </el-table-column>
      <el-table-column
        prop="attr_name"
        label="属性名称">
      </el-table-column>
      <el-table-column
        label="操作">
      <template slot-scope="scope">
           <el-button type="primary" icon="el-icon-edit" size="mini" @click="showDialog(scope.row.attr_id)">操作</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParamsData(scope.row.attr_id)">删除</el-button>
      </template>
      </el-table-column>
    </el-table>
    </el-tab-pane>
  </el-tabs>
    </el-card>
    <el-dialog
  :title="'添加'+ titleText"
  :visible.sync="addDialogVisible"
  width="50%" @close="addDialogVisibleClosed">
  <el-form :model="addParams" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
  <el-form-item :label="titleText" prop="attr_name">
    <el-input v-model="addParams.attr_name"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParamsCause">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  :title="'修改'+ titleText"
  :visible.sync="editDialogVisible"
  width="50%"
  @close="editDialogVisibleClosed">
  <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
  <el-form-item :label="titleText" prop="attr_name">
    <el-input v-model="editForm.attr_name"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParamsCause">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
    data(){
       return {
            catelist:[],
            cateCascaderId:[],
            cascaderProps:{
                label: 'cat_name',
                value: 'cat_id',
                children: 'children'
            },
            activeName:'many',
            manyactiveName:[],
            onlyactiveName:[],
            addDialogVisible:false,
            addParams:{
                attr_name:''
            },
            addParamsRules:{
                attr_name:  { required: true, message: '请输入参数名称', trigger: 'blur' }
            },
            editForm:{

            },
            editFormRules:{
                attr_name:  { required: true, message: '请输入参数名称', trigger: 'blur' }
            },
            editDialogVisible:false
       }
    },
    methods:{
        async getCateList(){
           const {data:res}=await this.$http.get('categories')
           if(res.meta.status!==200){
               return this.$message.error('获取失败')
           }
           this.catelist=res.data
        },
        handleChange(){
             this.getParamsList()
        },
        handleClick(){
            this.getParamsList()
        },
        async getParamsList(){
             if (this.cateCascaderId.length !== 3) {
        // 因为cateKeys与选择框有v-model双向数据绑定 所以将此处定义为空数组 那么将不会显示非三级分类
        this.cateCascaderId = []
        // 当选择的不是三级分类是 需要将下面已经出现的数据 清空
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
           const{data:res}= await this.$http.get(`categories/${this.cateId}/attributes`,{
               params:{
                   sel:this.activeName
               }
           })
           if(res.meta.status!==200){
               return this.$message.error('获取失败')
           }
           res.data.forEach(item=>{
                item.attr_vals= item.attr_vals?item.attr_vals.split(' '):[]
            item.inputVisible=false
             item.inputValue = ''
           })
          if(this.activeName==='many'){
               this.manyactiveName=res.data
          }else{
              this.onlyactiveName=res.data
            }
        },
         addDialogVisibleClosed(){
        this.$refs.addParamsRef.resetFields()
            },
        addParamsCause(){
        this.$refs.addParamsRef.validate(async valid=>{
            if(!valid) return 
            const {data:res}=await this.$http.post(`categories/${this.cateId}/attributes`,{
                attr_name:this.addParams.attr_name,
                attr_sel:this.activeName
            })
    if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.getParamsList()
        this.addDialogVisible = false
                 })
            },
        async handleInputConfirm(row){
             if(row.inputValue.trim().length===0){
                 row.inputVisible=false
                 row.inputValue=''
                 return 
             }
             row.attr_vals.push(row.inputValue.trim())
             row.inputValue=''
             row.inputVisible=false
            const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                 attr_name:row.attr_name,
                 attr_sel:row.attr_sel,
                 attr_vals:row.attr_vals.join(' ')
             })
             if (res.meta.status !== 200) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
         },
         showInput(row) {
        row.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        })},
        async  handleRemoveTag(i,row){
            const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                 attr_name:row.attr_name,
                 attr_sel:row.attr_sel,
                 attr_vals:row.attr_vals.splice(i,1).join(' ')
             })
             if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
        },
        async showDialog(id){
         const{data:res}=  await this.$http.get(`categories/${this.cateId}/attributes/${id}`,{
             params:{
                 attr_sel:this.activeName
             }
         })
         if (res.meta.status !== 200) {
        return this.$message.error('查询参数失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
        },
        editDialogVisibleClosed(){
        this.$refs.editFormRef.resetFields()
        },
        editParamsCause(){
            this.$refs.editFormRef.validate(async valid=>{
                if(!valid) return
              const{data:res}=await  this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
                    attr_name:this.editForm.attr_name,
                    attr_sel:this.activeName
                })
        if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
        }
        this.$message.success('修改参数成功')
        this.getParamsList()
        this.editDialogVisible = false
            })
           
        },
        async removeParamsData(id){
          const confirmResult=  await  this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirmResult!=='confirm'){
            return this.$message.info('取消删除')
        }
        const {data:res}=await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getParamsList()
        }

    },
    created(){
        this.getCateList()
    },
    computed:{
        isDisable(){
            if(this.cateCascaderId.length!==3){
                return true
            }
            return false
        },
        cateId(){
            if(this.cateCascaderId.length===3){
                return this.cateCascaderId[2]
            }
            return null
        },
        titleText(){
            if(this.activeName==='many'){
                return '动态参数'
            }else{
                return '静态属性'
            }
        }
    }
}
</script>

<style>
.row {
  margin-top: 15px;
  margin-bottom: 15px;
}
.el-tag {
  margin: 15px;
}
.input-new-tag {
  width: 110px;
}
</style>
